/**
 * 公司个性设置
 */
require(['zTreeCheckbox','select2', 'validator', 'ajaxfileupload'], function () {
	var userInfo = commonFun.execParentMethod("getUserInfo");               //当前登录用户信息
	//如果是最高管理员登录,可以让其看到所属公司
	var isAdminRole = userInfo.isAdminRole;                                 //是否超级管理员
	
	var sysCorpTreeObj = {},												//公司树
		$sysCorpForm = $("#sysCorpForm"),									//公司表单
		$sysCorpTree = $("#sysCorpTree"),corpId;									//公司树对应页面元素
	
	$("#img").on('click',function(){
		$("#logo").click();
	});
	
	//获得节点数据，并且生成左侧的树
	function initsysCorpTree(nodeId){
		var node;
		$.ajaxExt({
			url : "/sysCorpInfo/getJurisdictionCorpInfoList.htm"
		}).done(function(data){
//			console.info(data);
			if(isAdminRole === '1'){
				if (!data) {
					data = [];
				}
				// 树的参数配置
				var setting = {
					data: {
						key: {
							name: "corpName"
						},
						simpleData: {
							enable: true,
							idKey: "corpId",
							pIdKey: "parentCorpId",
							rootPId: 0
						}
					},
					view: {
						showIcon: true
					},
					callback: {
						onClick: sysCorpTreeClick
					}
				};
				//生成树
				sysCorpTreeObj = $sysCorpTree.createTree(setting, data, {search: $('#searchlabel')});//$.fn.zTree.init($sysCorpTree, setting, data);
				sysCorpTreeObj.expandAll(true);
				if(typeof nodeId !== "undefined"){//选中对应节点
					sysCorpTreeObj.setting.view.expandSpeed = "";
					sysCorpTreeObj.setting.view.expandSpeed = "fast";
					node = sysCorpTreeObj.getNodesByFilter(function(node) { return node.corpId == nodeId; }, true);
//					sysCorpTreeObj.selectNode(node,false);
//					sysCorpTreeClick(null,node.corpId,node,true);
				}else{//选中第一个节点
//					sysCorpTreeObj.expandAll(true);
					node = sysCorpTreeObj.getNodesByFilter(function(node) { return node.level == 0; }, true);
				}
				sysCorpTreeObj.selectNode(node,false);
				sysCorpTreeClick(null,node.corpId,node,true);
			}else{
				$("#left").hide();
//				setFormValues(data);
				$("#corpCd").attr("readonly", true);
				$("#enabledSt0").attr("disabled", true);
				$("#enabledSt1").attr("disabled", true);
				$("#corpType").attr("disabled", true);
			}
		});
	}
	
	function init() {
		$("#sysCorpForm").initForm();
		$(window).on('resize', initHeight).trigger('resize');
	    $('.slide-panel').on('click', function () {
	        $('#left').css('margin-left', $(this).toggleClass('slide-panel-active').hasClass('slide-panel-active') ? -250 : 0);
	    });
	}
	
	/**
	 * 进行初始化工作
	 */
	function initHeight(){
		var height = $(window).height();
		$sysCorpTree.parent().height(height - 45);
		$sysCorpTree.height(height - 55);
		$('#right').height(height);
	}
	
	/**
	 * 点击树节点
	 */
	function sysCorpTreeClick(event, treeId, treeNode,clickFlag){
		//右侧的“保存”按钮，将会变成更新的功能
		if(treeNode.level === 0){
			$("#delete").hide();
		}else{
			// 显示删除按钮
			$("#delete").show();
		}
		//对应填充右侧数据
		fillfn(treeNode);
	}
	
	/**
	 * 点击左侧机构列表，填充右侧信息
	 */
	var fillfn = function(item) {
		//通过点击的节点，获得父节点名称，显示在右侧的上级机构框中
		var treeNode = sysCorpTreeObj.getSelectedNodes()[0]; // 获取当前节点
//		console.info(treeNode.corpId);
		corpId = treeNode.corpId;
		$.ajaxExt({
			url :"/sysCorpInfo/loadCorpLogo.htm",
			data:{"corpId":corpId}
		}).done(function(data){
//			console.info(data.logoPath);
			if(typeof(data.logoPath)=="undefined"){
				$("#img").attr("src",'../content/images/logo_06.png');
			}else{
				$("#img").attr("src",$.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?uploadPath=" + data.logoPath);
			}
			if(typeof(data.carNameMode) == 'undefined'){
				data.carNameMode = 1;
			}
			//选中radio
			$("input[name='radio'][value='"+data.carNameMode+"']").prop("checked",true);
		});
		


	};
	
	
	//图片上传
    window.upload = function (el) {
    	$.ajaxFileUpload({
            url: $.getProjectName() + "/sysCorpInfo/uploadImage.htm",//需要链接到服务器地址
            secureuri: false,
            fileElementId: 'logo',//文件选择框的id属性
            data: {//加入的文本参数
                "uploadPath": "/files/upload/logo/" 
            },
            dataType: 'text',   //json
            success: function (data, status) {
            	//判断是否是ie浏览器
            	var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
            	var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器
            	var isFF = userAgent.indexOf("Firefox") > -1
            	if (isEdge || isFF) { 
            		if(data.length == 54){
            			var data1 = JSON.parse(data);
                        $.messager.alert("错误", data1.msg, "error");
            		}
            		$('#img').attr("src", $.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?v="+Math.random()+"&uploadPath=" + data.substring(2));
                    $('#logoPath').val(data.substring(2));
            	}else if(data.indexOf("pre") > 0){
            		console.info(1);
            		data = data.replace(/<\/*?pre[^<>]*>/, '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀
                    //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
                    if (data.substring(0, 1) == 0) {
                        $('#img').attr("src", $.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?v="+Math.random()+"&uploadPath=" + data.substring(2));
                        $('#logoPath').val(data.substring(2));
                    } 
            	}else{
            		var data1 = JSON.parse(data);
                    $.messager.alert("错误", data1.msg, "error");
            	}
            },
            error: function (data, status, e) {
//                alert(data.responseText);
                $.messager.alert("错误", "上传图片失败", "error");
            }
        });
    };
    //一点击就加载公司已有logo和车辆显示方式
    $.ajaxExt({
		url :"/sysCorpInfo/loadCorpLogo.htm"
	}).done(function(data){
//		console.info(data.logoPath);
		if(typeof(data.logoPath)=="undefined"){
			$("#img").attr("src",'../content/images/logo_06.png');
		}else{
			$("#img").attr("src",$.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?uploadPath=" + data.logoPath);
		}
//		console.info(data.carNameMode);
		$("input[name='radio'][value='"+data.carNameMode+"']").attr("checked","checked");
	});
    
   
    
    //恢复默认云总线图片
    $("#restore").on('click',function(){
    	$('#img').attr("src",'../content/images/logo_06.png'),
    	$('#logoPath').val('');
    });
    
  $("#save").on('click',function(){
//	  console.info($('#logoPath').val());
//	  console.info($("input[type='radio']:checked").val());
	  $.ajaxExt({
		  url:"/sysCorpInfo/saveCorpLogo.htm",
		  data:{"url":$('#logoPath').val(),"carNameMode":$("input[type='radio']:checked").val(),"corpId":corpId}
	  }).done(function(data){
		  $.messager.alert("提示",data, "info")
	  });
  }); 
  
  initsysCorpTree();

  init();
  
});